"""
-*- coding: utf-8 -*-
@Author  : Link
@Time    : 2022/12/20 11:22
@Site    :
@File    : qt_ui_test.py
@Software: PyCharm
@Remark  :
"""
import os
import sys
import pickle
import unittest

import re
import translate
import json

from PySide2.QtCore import Qt, QTimer
from PySide2.QtWidgets import QApplication, QDialog
from PySide2.QtTest import QTest

from app_test.test_utils.log_utils import Print
from app_test.test_utils.mixins import Hdf5DataLoad
from app_test.test_utils.wrapper_utils import Tester
from chart_core.chart_pyqtgraph.poll import ChartDockWindow
# from chart_core.chart_pyqtgraph.ui_components.ui_select_bin_dialog import SelectBinDialog
from common.app_variable import TestVariable
from common.li import SummaryCore, Li
from common.stdf_interface.stdf_parser import SemiStdfUtils
from ui_component.ui_analysis_stdf.ui_components.ui_data_group import DataGroupWidget
from ui_component.ui_analysis_stdf.ui_components.ui_file_load_widget import FileLoadWidget
from ui_component.ui_analysis_stdf.ui_components.ui_table_load_widget import TableLoadWidget
from ui_component.ui_analysis_stdf.ui_components.ui_tree_load_widget import TreeLoadWidget
from ui_component.ui_analysis_stdf.ui_stdf import StdfLoadUi
from ui_component.ui_common.ui_console import ConsoleWidget
from ui_component.ui_main.ui_main import Main_Ui
from ui_component.ui_main.ui_setting import SettingWidget

QtUiCaseAuto = False


class QtUiCase(unittest.TestCase, Hdf5DataLoad):
    """
    测试UI是否可以应对工程师使用
    """
    li: Li = Li()
    summary: SummaryCore = SummaryCore()

    @Tester()
    def test_console_ui(self):
        app = QApplication.instance()
        if app is None:
            app = QApplication(sys.argv)
        my_win = ConsoleWidget()
        my_win.show()
        app.exec_()

    @Tester()
    def test_setting_ui(self):
        app = QApplication.instance()
        if app is None:
            app = QApplication(sys.argv)
        win = SettingWidget()
        win.show()
        app.exec_()

    def test_stdf_load_ui(self):
        """
        选取数据
        :return:
        """
        app = QApplication.instance()
        if app is None:
            app = QApplication(sys.argv)
        win = FileLoadWidget(self.summary)
        win.directory_select_test(TestVariable.STDF_FILES_PATH)
        win.show()
        if QtUiCaseAuto:
            QTest.mouseClick(win.pushButton, Qt.LeftButton)
            QTest.mouseClick(win.pushButton_3, Qt.LeftButton)
            QTest.mouseClick(win.comboBox, Qt.LeftButton)
            QTimer.singleShot(1000, lambda: win.close())
        app.exec_()
        self.assertEqual(True, win.summary.ready)

    @Tester(
        ["test_stdf_load_ui"],
        exec_time=True,
        skip_args_time=True,
    )
    def test_stdf_tree_ui(self):
        """
        将数据处理后加载到Tree上用于选取
        :return:
        """
        app = QApplication.instance()
        if app is None:
            app = QApplication(sys.argv)
        win = TreeLoadWidget(li=self.li, summary=self.summary)
        win.set_tree()
        win.show()
        # TODO: pushButton后的操作和解析可以改成多线程, 传递一个进度条
        if QtUiCaseAuto:
            # win.summary.add_custom_node(TreeUtils.get_tree_ids(win.treeWidget), "TEST")
            # win.set_tree()
            QTimer.singleShot(0, lambda: QTest.mouseClick(win.pushButton, Qt.LeftButton))
            # QTimer.singleShot(3000, lambda: win.close())
        app.exec_()
        Print.print_table(win.li.capability_key_list)

    @Tester(
        ["test_stdf_tree_ui"],
        exec_time=True,
        skip_args_time=True,
    )
    def test_table_capability_ui(self):
        """
        加载从TreeLoad中选取的数据, 并解析
        测试改变Limit后重算Rate
        测试删除选中limit外的数据 -> 变慢了好多啊
        测试只对选中的数据进行分析
        :return:
        """
        app = QApplication.instance()
        if app is None:
            app = QApplication(sys.argv)
        win = TableLoadWidget(self.li, self.summary)
        win.cal_table()
        if QtUiCaseAuto:
            "更改limit后重算yield"
        win.show()
        app.exec_()

    @Tester(
        ["test_stdf_tree_ui"],
        exec_time=True,
        skip_args_time=True,
    )
    def test_group_load(self):
        app = QApplication.instance()
        if app is None:
            app = QApplication(sys.argv)
        win = DataGroupWidget(self.li)
        win.checkbox_changed()
        win.show()
        app.exec_()

    @Tester(

    )
    def test_main_ui_stdf(self):
        """

        :return:
        """
        app = QApplication.instance()
        if app is None:
            app = QApplication(sys.argv)
        win = StdfLoadUi()
        if QtUiCaseAuto:
            "更改limit后重算yield"
        win.show()
        app.exec_()

    @Tester(

    )
    def test_ui_stdf_save_CsvOrXlsx(self):
        """
        数据保存为csv/(xlsx -> 用excel打开csv并调用vba)
        使用pandas的unstack看好用不.
        :return:
        """
        pass

    @Tester(

    )
    def test_ui_stdf_show_limit(self):
        """
        Limit之间的差异
        :return:
        """
        pass

    @Tester(

    )
    def test_app_ui(self):
        app = QApplication.instance()
        if app is None:
            app = QApplication(sys.argv)
        app.setApplicationName("IC DATA ANALYSIS")
        win = Main_Ui()
        win.show()
        app.exec_()


class QtUiHdf5Case(unittest.TestCase, Hdf5DataLoad):
    """
    数据解析, 给UI传递参数, 简单测试
    """
    li: Li = Li()
    summary: SummaryCore = SummaryCore()

    def test_something(self):
        self.assertEqual(True, True)

    @Tester(
        [],
        exec_time=True,
        skip_args_time=True,
    )
    def test_stdf_read(self):
        """
        原始STDF数据
        :return:
        """
        print(SemiStdfUtils.get_lot_info_by_semi_ate(TestVariable.STDF_PATH))

    @Tester(
        [],
        exec_time=True,
        skip_args_time=True,
    )
    def test_stdf_load_ui(self, **kwargs):
        """
        原始STDF数据
        :param kwargs:
        :return:
        """

    @Tester(
        [],
        exec_time=True,
        skip_args_time=True,
    )
    def test_tree_load(self, **kwargs):
        pass

    def load_table_data(self):
        if not os.path.exists(TestVariable.TABLE_PICKLE_PATH):
            Print.Warning("No Path")
            self.assertEqual(True, False)
        with open(TestVariable.TABLE_PICKLE_PATH, 'rb') as file:
            li = pickle.loads(file.read())
        return li

    @Tester(
        ["load_table_data"],
        exec_time=True,
        skip_args_time=True,
    )
    def test_read_table_data(self, **kwargs):
        li = kwargs.get("load_table_data")
        if li is None:
            Print.Warning("No Data")
            self.assertEqual(True, False)
        Print.print_table(li)
        self.li.capability_key_list = li

    @Tester(
        ["test_read_table_data"],
        exec_time=True,
        skip_args_time=True,
    )
    def test_table_load(self):
        app = QApplication(sys.argv)
        win = TableLoadWidget(self.li, self.summary)
        win.cal_table()
        win.show()
        app.exec_()

    @Tester()
    def test_chart_dock_widget(self):
        app = QApplication(sys.argv)
        win = ChartDockWindow(self.li)
        win.show()
        app.exec_()


class QtUiWebCase(unittest.TestCase):

    @Tester(
        [],
        exec_time=True,
        skip_args_time=True,
    )
    def test_something(self):
        self.assertEqual(True, True)

    # @Tester()
    # def test_select_dialog(self):
    #     app = QApplication.instance()
    #     if app is None:
    #         app = QApplication(sys.argv)
    #     dia = SelectBinDialog()
    #     dia.show()
    #     if dia.exec_() == QDialog.Accepted:
    #         print(dia.checkBox.isChecked())
    #         print(dia.spinBox.value())

    def test_search_qt_designer_py_file(self):
        """
        查找所有的ui_designer文件夹下的ui_开头的py文件
        :return:
        """
        root_dir = r"C:\Users\rkiam\PycharmProjects\PlotStdf"
        # 遍历根目录下的所有子目录
        for subdir, dirs, files in os.walk(root_dir):
            # 在每个子目录下创建一个名为“example.txt”的文件
            path_name = subdir.split("\\")
            if path_name[-1] == "ui_designer":
                for file in files:
                    _, suffix = os.path.splitext(file)
                    if suffix != '.py':
                        continue
                    print(file)

    def to_chinese(self, string):
        x = json.loads('{"s": "%s"}' % string)
        return x["s"]

    def test_translate_single_qt_designer_py_file(self, single_path=""):
        """
        1. 扫描文件中是否含有def retranslate(self): 这个函数
        2. 若没有这个函数, 开始在结尾处加入retranslate函数
        3. 添加转换代码
        :param single_path:
        :return:
        """

        t = translate.Translator(to_lang="en", from_lang="zh-CH")
        pattern = re.compile(r"self.+\(QCoreApplication.translate\(.+")
        unicode_pattern = r'u"(.*?)"'
        if single_path == "":
            single_path = \
                r"C:\Users\rkiam\PycharmProjects\PlotStdf\ui_component\ui_analysis_stdf\ui_designer\ui_home_load.py"
        with open(single_path, "r", encoding="utf-8") as f:  # 打开文件
            data = f.readlines()  # 读取文件

        for line in data:
            if "def retranslate(self)" in line:
                return

        Print.Warning("执行中英文转换")
        def_lines = []
        for line in data:
            pat = pattern.findall(line)
            if pat:
                result = re.search(unicode_pattern, line)
                if not result:
                    continue
                Print.Warning(line)
                old_string = result.group(1)
                Print.Warning(old_string)
                new_string_ch = self.to_chinese(result.group(1))
                Print.Debug(new_string_ch)
                new_string = t.translate(new_string_ch).title()
                old_string = "u\"" + old_string + "\""
                new_string = "u\"" + new_string + "\""
                new_string = line.replace(old_string, new_string)
                Print.Debug(new_string)
                def_lines.append(new_string)

        Print.Warning("加入数据到py文件中")
        # 打开文件，如果文件不存在则创建
        with open(single_path, 'a', encoding="utf-8") as f:
            # 写入数据
            f.write("\n")
            f.write("    def retranslate(self):\n")
            for each in def_lines:
                f.write(each)

    def test_translate_qt_designer_py_file(self):
        """
        1.查找所有的ui_designer文件夹下的ui_开头的py文件
        2.使用正则表达式处理
        3.使用机器进行翻译
        4.将函数写入到py文件中
        :return: 
        """
        import translate
        t = translate.Translator(to_lang="en", from_lang="zh-CH")
        print(t.translate(u"120010STDF\u6570\u636e\u6587\u4ef6\u8f7d\u5165").title())
        print(t.translate("取消数据保存").title())

    def test_mass_translate_qt_designer_py_file(self):
        """
        查找所有的ui_designer文件夹下的ui_开头的py文件
        :return:
        """
        root_dir = r"C:\Users\rkiam\PycharmProjects\PlotStdf"
        # 遍历根目录下的所有子目录
        for subdir, dirs, files in os.walk(root_dir):
            # 在每个子目录下创建一个名为“example.txt”的文件
            path_name = subdir.split("\\")
            if path_name[-1] == "ui_designer":
                for file in files:
                    _, suffix = os.path.splitext(file)
                    if suffix != '.py':
                        continue
                    # self.test_translate_single_qt_designer_py_file()
                    file_path = os.path.join(subdir, file)
                    Print.Warning("解析文件: -> " + file_path)
                    self.test_translate_single_qt_designer_py_file(file_path)
